package com.dubbo.rpcserver;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * create by yongli on 2021-10-23 16:20
 * rpc的server端调用
 * 不使用spring框架，方便启动
 */

public class RpcServer {
    private final int port;

    public RpcServer() {
        this.port = 8080;
    }

    public RpcServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws Exception {
        RpcServer rpcServer = new RpcServer();
        rpcServer.start();
    }

    /**
     * 启动服务器的代码，开始监听端口，处理业务
     */
    public void start() throws Exception {
        final EchoHandler echoHandler = new EchoHandler();
        EventLoopGroup group = new NioEventLoopGroup();

        // 接入连接
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(group)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    // 添加handler
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(echoHandler);
                        }
                    });
            ChannelFuture future = b.bind().sync();
            future.channel().closeFuture().sync();
        } finally {
            // 都在说明这是一个异步方法
            group.shutdownGracefully().sync();
        }

    }


}
